package com.ee.chat.api.listener.mq;

import com.alibaba.fastjson.JSONObject;
import com.aliyun.openservices.ons.api.Action;
import com.aliyun.openservices.ons.api.ConsumeContext;
import com.aliyun.openservices.ons.api.Message;
import com.aliyun.openservices.ons.api.MessageListener;
import com.ee.chat.api.service.impl.IMServiceImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Map;

@Component
public class WordMQListener implements MessageListener {
    private Logger log = LoggerFactory.getLogger(WordMQListener.class);

    @Resource(name = "stringRedisTemplate")
    StringRedisTemplate redisTemplate;
    @Resource
    IMServiceImpl imService;

    @Override
    public Action consume(Message message, ConsumeContext consumeContext) {
        log.info("消费敏感词或关键词消息");
        try {
            String tag = message.getTag();
            if("sensitiveWord".equals(tag)){    //敏感词消息
                Object sensitiveWordObj = redisTemplate.opsForHash().get("data", "sensitiveWord");
                Map<String, Object> sensitiveWordMap = JSONObject.parseObject(sensitiveWordObj+"", Map.class);

                imService.setSensitiveWordMap(sensitiveWordMap);

            }else if("keyWord".equals(tag)){    //关键词消息
                Object keyWordObj = redisTemplate.opsForHash().get("data", "keyWord");
                Map<String, Object> keyWordMap = JSONObject.parseObject(keyWordObj+"", Map.class);

                imService.setKeyWordMap(keyWordMap);
            }

            return Action.CommitMessage;
        }catch (Exception e){
            log.error("消息消费失败", e);
            return Action.ReconsumeLater;
        }
    }


}
